<template>
    <div class="user-recharge-voucher">
        <div class="money">
            <ul class="form__box">
                <li class="form__item">
                    <span class="form__key">充值点券数</span>
                    <div class="form__value">
                        <input type="tel" v-model='rechargeMoney' placeholder="50点起" @input='calcRecharge'>
                    </div>
                </li>
            </ul>
            <div class='explains'>
                <p class='explain'>点券售价1元/点</p>
                <p class='explain' v-if='freeScore'>系统赠送<span>{{freeScore | toYuan('int')}}点</span>, 共获得<span>{{totalReceiveScore | toYuan('int')}}点</span></p>
            </div>
        </div>

        <!-- <p class="tips">充值手续费2.5元/笔，单次充值≥500元免手续费</p> -->

        <div class="confirm-button">
            <span class="button long" @click='confirm' :class='{disabled : !agreementCheck}'>充值</span>
        </div>

        <div class="form__agreement">
            <check-box v-model='agreementCheck'><span class='form__agreement-text'>已阅读并同意 <em @click.stop='showAgreement = true'>《购买服务协议》</em> </span></check-box>
        </div>

        <login
            :show='showLogin'
            @close='showLogin = false'></login>

        <pay-detail
            :amount='rechargeMoneyToFen'
            :show='showPayDetail'
            @close='showPayDetail=false'
            @finish='payDetailFinish'></pay-detail>

        <pay-password
            v-if='userInfo.user'
            :show='showPayPassword'
            @close='showPayPassword=false'
            @finish='payFinish'></pay-password>

        <sms-code
            v-if='userInfo.user'
            :show='showSmsCode'
            type='SCORE_CHARGE'
            :mobile='userInfo.user.mobile'
            @close='showSmsCode=false'
            @finish='smsFinish'></sms-code>

        <agreement
            type='buy'
            :show='showAgreement'
            @close='showAgreement=false'></agreement>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import payPassword from '../components/PayPassword.vue'
    import payDetail from '../components/PayDetail.vue'
    import smsCode from '../components/SmsCode.vue'
    import  { mapGetters, mapActions }  from 'vuex'
    import bankCard from '../filters/filter-bankCard'
    import toYuan from '../filters/filter-toYuan'
    import agreement from '../components/Agreement.vue'
    import checkBox from '../components/CheckBox.vue'
    import { getQueryString } from '../utils/utils'
    import login from '../components/Login.vue'
    import { addLenderValidation, resetAccountPasswordValidation, operatorEditValidation } from '../validation/validation'
    import { scoreApi, userApi, payApi } from '../api/api'
    import moment from 'moment'

    export default {
        components:{
            payPassword,
            checkBox,
            smsCode,
            payDetail,
            agreement,
            login
        },
        filters:{
            bankCard,
            toYuan
        },
        data() {
            return {
                isProd:!getQueryString().mode,
                showLogin:false,
                rechargeMoney:'',
                passwordPass:false,
                password:'',
                payWay:'',
                showPayPassword:false,
                showSmsCode:false,
                showPayDetail:false,
                showAgreement:false,
                agreementCheck:true,
                payId:'',
                freeScore:'',
                totalReceiveScore:'',
                smsCode:'',
                cardNo:''
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo'
            ]),
            userInfo(){
                return this.localInfo.userInfo
            },
            rechargeMoneyToFen(){
                return (this.rechargeMoney*100).toFixed(2)
            }
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip',
                'setUserInfo'
            ]),

            // function
            confirm(){
                if(!this.userInfo.isPay || this.userInfo.isExpired){
                    this.setMsgTip({
                        text:'请先完成信用报告',
                        type:'info'

                    })
                    this.$router.push({
                        name:'user-credit-report-index'
                    })
                    return
                }
                // return
                if(this.rechargeMoney == ''){
                    this.setMsgTip({
                        text:'充值点券不能为空',
                        type:'warn'
                    })
                    return
                }
                if(this.isProd && this.rechargeMoney < 50){
                    this.setMsgTip({
                        text:'充值点券不能小于50点',
                        type:'warn'
                    })
                    return
                }
                this.$ga.event({
                  eventCategory: 'Rechargebtn_v',
                  eventAction: 'click',
                  eventLabel: '充值按钮点击量'
                })
                // if(this.rechargeMoney < 100){
                //     this.setMsgTip({
                //         text:'充值金额不能不能小于100元',
                //         type:'warn'
                //     })
                //     return
                // }
                this.showPayDetail = true
            },
            payDetailFinish(payObject){
                if(payObject.payType == 0){
                    this.payWay = 'CHARGE'
                    this.cardNo = payObject.cardNo
                    this.recharge()
                }
                else{
                    this.payWay = 'BALANCE'
                    this.showPayPassword = true
                }
                this.showPayDetail = false

            },
            payFinish(password){
                this.password = password
                this.passwordPass = true
                this.showPayPassword = false
                if(this.payWay == 'BALANCE'){
                    this.showSmsCode = true
                }
                else{
                    this.recharge()
                }
            },
            smsFinish(smsCode){
                this.smsCode = smsCode
                this.showSmsCode = false
                this.recharge()
            },
            recharge(){
                this.showLoading()
                scoreApi.charge({
                    chargeAmount:Math.round(this.rechargeMoney * 100),
                    tradePassword:this.password,
                    smsCode:this.smsCode,
                    payWay:this.payWay
                })  
                .then(result=> {
                    this.hideLoading()
                    if(_.isEmpty(result)){
                        this.setMsgTip({
                            text:'充值点券成功！',
                            type:'success'
                        })
                        history.back()
                        return
                    }
                    this.payId = result.charge.payId
                    this.pay()
                })
                .catch(error=> {
                    console.error(error);
                    this.hideLoading()
                })
            },
            calcRecharge(){
                if(!this.rechargeMoney) return
                if(this.rechargeMoney > 1000000){
                    this.rechargeMoney = 1000000
                }
                scoreApi.calc({
                    chargeAmount:Math.round(this.rechargeMoney * 100),
                })
                .then(result=> {
                    this.freeScore = result.freeScore
                    this.totalReceiveScore = result.totalReceiveScore
                })
                .catch(error=> {
                    console.error(error);
                })
            },
            pay(){
                payApi.payBankCard({
                    payId:this.payId,
                    cardNo:this.cardNo,
                    returnUrl:location.href
                })
                .then(result=> {
                    location.href = result.payParam.url
                })
                .catch(error=> {
                    console.error(error);
                    this.hideLoading()
                })
            },
        },
        created(){
            if(!this.userInfo.user){
                this.showLogin = true
            }
            let status = this.$route.query.status
            let uuid = this.$route.query.uuid 
            let name = this.$route.query.name 
            if(status == 'fail'){
                this.setMsgTip({
                    text:'充值失败！',
                    type:'error'
                })
            }
            if(status == 'success'){
                this.setMsgTip({
                    text:'充值成功！',
                    type:'success'
                })
                if(uuid){
                    this.$router.replace({
                        name:name,
                        params:{
                            id:uuid
                        }
                    })
                    return
                }
                this.$router.replace({
                    name:'user-index'
                })
            }
            // window.onunload = function(){};
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .user-recharge-voucher{
        .bank-list{
            background-color: #fff;
            margin-top: 16px;
        }
        .bank__item{
            padding: 16px;
            display: flex;
            justify-content: space-between;
            align-items:center;
        }
        .bank__info{
            display: flex;
            img{
                width: 48px;
                height: 48px;
                border-radius:50%;
            }
            .bank__text{
                padding-left: 16px;
                p{
                    @extend %font-subhead;
                    color:$importColor;
                }
                span{
                    @extend %font-caption;
                    display: block;
                    padding-top: 2px;
                }
            }
        }
        .money{
            margin-top: 20px;
            position: relative;
            .explain{
                padding:8px 24px;
            }
        }
        .money__input{
            @extend %font-subhead;
            padding:15px 24px;
            width: 100%;
            box-sizing:border-box;
        }
        .tips{
            @extend %font-caption;
            padding: 12px 24px;
        }
        .confirm-button{
            padding:30px 24px 8px 24px;
        }
        .explains{
            display: flex;
            justify-content: space-between;
            span{
                color:$orange;
            }
        }
    }

</style>
